package cz.data.common.jackson;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import cz.data.common.core.DataRole;

import java.io.IOException;

public class DataRoleDeserializer extends JsonDeserializer<DataRole> {

    @Override
    public DataRole deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JacksonException {
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode jsonNode = mapper.readTree(jp);
        String id = this.readJsonNode(jsonNode, "id").asText(null);
        String dataScope = this.readJsonNode(jsonNode, "dataScope").asText(null);
        DataRole role = new DataRole();
        role.setId(id);
        role.setDataScope(dataScope);
        return role;
    }

    private JsonNode readJsonNode(JsonNode jsonNode, String field) {
        return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
    }
}
